package cn.zjjd.homeworkserver.controller;

import cn.zjjd.homeworkserver.service.UserService;
import cn.zjjd.homeworkserver.util.ReturnMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.zjjd.homeworkserver.pojo.User;
import java.util.List;

/**
 * @author: 小胡
 * @create: 2022/12/20
 * @Description:
 * @FileName: LoginController
 * @Version: 1.0
 */
@RestController
public class LoginController {
    @Autowired
    UserService userService;
    @PostMapping("/tologin")
    public ReturnMessage userLogin(String userName,String password){
        ReturnMessage rm = new ReturnMessage();
        List<User> users = userService.queryAllUser();
        for (User user:users) {
            if (user.getUserName().equals(userName) && user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))){
                rm.setSuccess(true);
                return rm;
            }
        }
        rm.setSuccess(false);
        return rm;
    }
    @PostMapping("/toregister")
    public ReturnMessage userRegister(String userName,String password,String telephone,String otherMessage){
        ReturnMessage rm = new ReturnMessage();
        List<User> users = userService.queryAllUser();
        for (User user:users) {
            if (user.getUserName().equals(userName)){
                rm.setSuccess(false);
                return rm;
            }
        }
        String md5pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        User user = new User(userName,md5pwd,telephone,otherMessage,"普通用户");
        userService.addUser(user);
        rm.setSuccess(true);
        return rm;
    }
    @PostMapping("/tologout")
    public ReturnMessage userLogout(){
        ReturnMessage rm = new ReturnMessage();
        //清除缓存等
        return rm;
    }
}
